package com.beauty.ui;

import java.util.LinkedList;
import s.d.f.AdManager;
import s.d.f.onlineconfig.OnlineConfigCallBack;
import s.d.f.st.SpotManager;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.FloatMath;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.beauty.api.ApiClient;
import com.beauty.common.AnimateFirstDisplayListener;
import com.hk.beauty.R;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class ImagePager extends Activity {

	private final String STATE_POSITION = "STATE_POSITION";
	private LinkedList<String> listImage;
	private String albumid;
	ViewPager pager;
	Bundle bundle;
	RelativeLayout Back_Bottom;
	Button pager_btn_back;
	public static String OpenKey="1";//开:1 ; 关:0
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息栏
		setContentView(R.layout.ac_image_pager);

		pager = (ViewPager) findViewById(R.id.pager);
		Back_Bottom = (RelativeLayout) findViewById(R.id.Back_Bottom);
		pager_btn_back = (Button) findViewById(R.id.pager_btn_back);

		bundle = getIntent().getExtras();
		assert bundle != null;
		albumid = bundle.getString("ablumid");
		// 开启线程获取数据
		new Thread(new ReceiveThread()).start();
		// 屏幕滑动监测
		pager.setOnPageChangeListener(new MyPagerChangeListener());

		pager_btn_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ImagePager.this.finish();
			}
		});

		LoadYouMiAd();

	}

	class ReceiveThread implements Runnable {
		@Override
		public void run() {
			listImage = ApiClient.getSingle().GetPicList(albumid);
			if (listImage != null) {
				handler.sendEmptyMessage(1);
			}
		}
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 1) {
				pager.setAdapter(new ImagePagerAdapter(listImage));
				pager.setCurrentItem(0);
			}
		}
	};

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt(STATE_POSITION, pager.getCurrentItem());
	}

	boolean misScrolled;

	class MyPagerChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int state) {
			switch (state) {
			case ViewPager.SCROLL_STATE_DRAGGING:
				misScrolled = false;
				break;
			case ViewPager.SCROLL_STATE_SETTLING:
				misScrolled = true;
				break;
			case ViewPager.SCROLL_STATE_IDLE:
				if (pager.getCurrentItem() == pager.getAdapter().getCount() - 1
						&& !misScrolled) {

					Back_Bottom.setVisibility(View.VISIBLE);
					if(OpenKey.equals("1")){
						SpotManager.getInstance(ImagePager.this).showSpotAds(ImagePager.this);
					}
				}
				if (pager.getAdapter().getCount() >= 9
						&& pager.getCurrentItem() == 4) {
					if(OpenKey.equals("1")){
						SpotManager.getInstance(ImagePager.this).showSpotAds(ImagePager.this);
					}
				}
				misScrolled = true;
				break;
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int arg0) {
		}
	}

	private class ImagePagerAdapter extends PagerAdapter {

		private LinkedList<String> images;
		private LayoutInflater inflater;

		ImagePagerAdapter(LinkedList<String> images) {
			this.images = images;
			inflater = getLayoutInflater();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public int getCount() {
			return images.size();
		}

		@Override
		public Object instantiateItem(ViewGroup view, int position) {
			View imageLayout = inflater.inflate(R.layout.item_pager_image,
					view, false);
			assert imageLayout != null;
			ImageView imageView = (ImageView) imageLayout
					.findViewById(R.id.image);
			final ProgressBar spinner = (ProgressBar) imageLayout
					.findViewById(R.id.loading);

			Main.imageLoader.displayImage(images.get(position), imageView,
					AnimateFirstDisplayListener.getOptions(),
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
							spinner.setVisibility(View.VISIBLE);
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
							String message = null;
							switch (failReason.getType()) {
							case IO_ERROR:
								message = "图片数据错误";
								break;
							case DECODING_ERROR:
								message = "图片不能被解析";
								break;
							case NETWORK_DENIED:
								message = "下载出错";
								break;
							case OUT_OF_MEMORY:
								message = "内存过载";
								break;
							case UNKNOWN:
								message = "未知错误";
								break;
							}
							Toast.makeText(ImagePager.this, message,
									Toast.LENGTH_SHORT).show();

							spinner.setVisibility(View.GONE);
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							spinner.setVisibility(View.GONE);
						}
					});
			imageView.setOnTouchListener(new TounchListener(imageView));

			view.addView(imageLayout, 0);
			return imageLayout;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view.equals(object);
		}

		@Override
		public void restoreState(Parcelable state, ClassLoader loader) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}
	}

	private class TounchListener implements OnTouchListener {
		ImageView imageView;

		public TounchListener(ImageView _imageView) {
			imageView = _imageView;
		}

		private PointF startPoint = new PointF();
		private Matrix matrix = new Matrix();
		private Matrix currentMaritx = new Matrix();

		private int mode = 0;// 用于标记模式
		private final int DRAG = 1;// 拖动
		private final int ZOOM = 2;// 放大
		private float startDis = 0;
		private PointF midPoint;// 中心点

		public boolean onTouch(View v, MotionEvent event) {

			switch (event.getAction() & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:
				mode = DRAG;
				currentMaritx.set(imageView.getImageMatrix());// 记录ImageView当期的移动位置
				startPoint.set(event.getX(), event.getY());// 开始点
				break;
			case MotionEvent.ACTION_MOVE:// 移动事件
				this.imageView.setScaleType(ImageView.ScaleType.MATRIX);
				if (mode == DRAG) {// 图片拖动事件
					float dx = event.getX() - startPoint.x;// x轴移动距离
					float dy = event.getY() - startPoint.y;
					matrix.set(currentMaritx);// 在当前的位置基础上移动
					matrix.postTranslate(dx, dy);
				} else if (mode == ZOOM) {// 图片放大事件
					float endDis = distance(event);// 结束距离
					if (endDis > 10f) {
						float scale = endDis / startDis;// 放大倍数
						matrix.set(currentMaritx);
						matrix.postScale(scale, scale, midPoint.x, midPoint.y);
					}
				}
				break;
			case MotionEvent.ACTION_UP:
				mode = 0;
				break;
			// 有手指离开屏幕，但屏幕还有触点(手指)
			case MotionEvent.ACTION_POINTER_UP:
				mode = 0;
				break;
			// 当屏幕上已经有触点（手指）,再有一个手指压下屏幕
			case MotionEvent.ACTION_POINTER_DOWN:
				mode = ZOOM;
				startDis = distance(event);
				if (startDis > 10f) {// 避免手指上有两个茧
					midPoint = mid(event);
					currentMaritx.set(imageView.getImageMatrix());// 记录当前的缩放倍数
				}
				break;
			}
			imageView.setImageMatrix(matrix);
			return true;
		}
	}

	/**
	 * 两点之间的距离
	 * 
	 * @param event
	 * @return
	 */
	private static float distance(MotionEvent event) {
		// 两根线的距离
		float dx = event.getX(0) - event.getX(0);
		float dy = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(dx * dx + dy * dy);
	}

	/**
	 * 计算两点之间中心点的距离
	 * 
	 * @param event
	 * @return
	 */
	private static PointF mid(MotionEvent event) {
		float midx = event.getX(0) + event.getX(1);
		float midy = event.getY(0) + event.getY(1);
		return new PointF(midx / 2, midy / 2);
	}

	/*
	 * 有米广告
	 */
	public void LoadYouMiAd() {
		// 初始化接口，应用启动的时候调用
		// 参数：appId, appSecret, 调试模式
		AdManager.getInstance(this).init("7cec00821e132b15",
				"1ec8262904ee96f5", false);

		// 加载插播资源
		SpotManager.getInstance(this).loadSpotAds();
		// 设置展示超时时间，加载超时则不展示广告，默认0，代表不设置超时时间
		SpotManager.getInstance(this).setShowInterval(20);// 设置20秒的显示时间间隔
		SpotManager.getInstance(this).setSpotOrientation(
				SpotManager.ORIENTATION_PORTRAIT);
		
		//OpenKey = AdManager.getInstance(this).syncGetOnlineConfig("OpenKey", "1");
		// 异步调用（可在任意线程中调用）
		AdManager.getInstance(this).asyncGetOnlineConfig("OpenKey", new OnlineConfigCallBack() {
		    @Override
		    public void onGetOnlineConfigSuccessful(String key, String value) {
		        // 获取在线参数成功
				OpenKey=value;
		    }
		    @Override
		    public void onGetOnlineConfigFailed(String key) {
		        // TODO Auto-generated method stub
		        // 获取在线参数失败，可能原因有：键值未设置或为空、网络异常、服务器异常
		    }
		});
	}

	@Override
	public void onBackPressed() {
		// 如果有需要，可以点击后退关闭插播广告。
		if (!SpotManager.getInstance(ImagePager.this).disMiss(true)) {
			super.onBackPressed();
		}
	}

	@Override
	protected void onStop() {
		// 如果不调用此方法，则按home键的时候会出现图标无法显示的情况。
		SpotManager.getInstance(ImagePager.this).disMiss(false);
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		SpotManager.getInstance(this).unregisterSceenReceiver();
		super.onDestroy();
	}
}